package org.tom.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.tom.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader("token"); // 从头消息中获取token
        if (token != null){  // 判断头消息中是否包含token
            Object obj = redisTemplate.opsForValue().get(token); // 从redis数据库中获取key为token的value
            if (obj!=null) {
                redisTemplate.opsForValue().set(token, obj, 30, TimeUnit.MINUTES); // 由于客户重新操作了页面，所以重新对获取到的value进行授权时间，
                return true;
            }
        }
        // 设置消息头才可以将写的信息传到前端
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter(); // 通过响应对象获取输出流
        writer.write("{\"success\":false,\"message\":\"noLogin\"}"); // 在输出流中写信息响应到前端
        writer.close();

        return false;
    }
}
